/**
 * Copyright 2019 吉鼎科技.

 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.easyplatform.utils.resource.impl;

import cn.easyplatform.lang.Streams;
import cn.easyplatform.lang.util.Disks;
import cn.easyplatform.utils.resource.GResource;

import java.io.File;
import java.io.InputStream;

/**
 * 记录了一个磁盘文件资源
 *
 * @author <a href="mailto:davidchen@epclouds.com">littleDog</a>
 */
public class FileResource extends GResource {

    private File file;

    public FileResource(File f) {
        this.file = f;
        this.name = f.getName();
    }

    public FileResource(String base, File file) {
        base = Disks.normalize(Disks.getCanonicalPath(base));
        if (base == null)
            base = "";
        else if (!base.endsWith("/"))
            base += "/";
        this.name = Disks.normalize(Disks.getCanonicalPath(file
                .getAbsolutePath()));
        this.name = this.name
                .substring(this.name.indexOf(base) + base.length()).replace(
                        '\\', '/');
        this.file = file.getAbsoluteFile();
    }

    public File getFile() {
        return file;
    }

    public FileResource setFile(File file) {
        this.file = file;
        return this;
    }

    public InputStream getInputStream() {
        return Streams.fileIn(file);
    }
}
